ReactJS Ultra For Beginners
🔄 The useEffect Hook
What is useEffect?
- A React Hook for handling side effects in functional components
- Replaces componentDidMount, componentDidUpdate, and componentWillUnmount
- Runs after every render by default
- Note: Some of the concepts in this sheet are more advanced then where we are now in the course, use this as an eternal cheatsheet for all useEffect related questions.
📝 Basic Syntax
import React, { useState, useEffect } from "react"; function UserProfile() { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { // Side effect code here fetchUserData(); }, []); // Empty dependency array = run only once return ( <div>{loading ? <p>Loading...</p> : <p>Welcome, {user?.name}!</p>}</div> ); }
🔑 Dependency Array
No dependency array (runs after every render):
useEffect(() => { console.log("This runs after every render"); });
Empty dependency array (runs only once):
useEffect(() => { console.log("This runs only once (like componentDidMount)"); }, []);
With dependencies (runs when dependencies change):
useEffect(() => { console.log("This runs when userId changes"); }, [userId]);
🎯 Common Use Cases
1. Data Fetching:
useEffect(() => { const fetchData = async () => { try { const response = await fetch("/api/users"); const data = await response.json(); setUsers(data); } catch (error) { console.error("Error fetching data:", error); } }; fetchData(); }, []); // Empty array = fetch once on mount
2. Event Listeners:
useEffect(() => { const handleResize = () => { setWindowSize({ width: window.innerWidth, height: window.innerHeight, }); }; window.addEventListener("resize", handleResize); // Cleanup function return () => { window.removeEventListener("resize", handleResize); }; }, []); // Empty array = add listener once
3. Timer/Interval:
useEffect(() => { const interval = setInterval(() => { setCount((prevCount) => prevCount + 1); }, 1000); // Cleanup function return () => clearInterval(interval); }, []); // Empty array = start timer once
⚠️ Important Rules
- Always include dependencies that are used inside useEffect
- Use cleanup functions for subscriptions, timers, and event listeners
- Don't call useEffect inside loops, conditions, or nested functions
- The cleanup function runs before the effect runs again
🔧 Cleanup Function
useEffect(() => { // Setup const subscription = someAPI.subscribe(); // Cleanup (runs before next effect or on unmount) return () => { subscription.unsubscribe(); }; }, []);
🎯 Best Practices
- Keep effects focused - one effect per concern
- Use the function form for state updates in effects
- Extract complex logic into custom hooks
- Always clean up subscriptions and timers
111 / 111 videos100% complete
Course Completed!
Great job! You've finished all videos.
Welcome to the Course
Intro to The Course
3:33How to Learn This Course
3:02What is React and Why You Should Learn It?
4:14Getting Started with React
Installing Nodejs
3:03Setting up a React Development Environment
4:30VSCode Extensions
3:17JavaScript Refresher - All JS You Need To Know Before React
Functions
5:39Ternary and Logical Operators
7:21Objects and Arrays
7:11Map and Filter Functions
7:15Array Function Key Prop
3:13String Templating
4:27Basic React Concepts
React Project Folder Structure
6:55An Intro To JSX
10:33What is the App Component?
2:46How to use Components?
10:23Lists in React
9:45CSS in React
9:10Component Project - Build A Simple Website
First React Project
3:34Making A Navbar
7:11Displaying Images
7:11Making the About Us Section
2:35Creating A Footer
3:38Intro To States In React
What is the useState Hook?
10:38What is the useState Hook? Part 2
4:42What is the useState Hook? Part 3
14:50Intro React Project - Task Tracker App
Beginner Project - Task Tracker App
35:03React Component Lifecycle
The Virtual Dom
1:50React Component Lifecycle
1:42The useEffect Hook
15:40The useEffect Hook Part 2
8:41